﻿using BaseDll;
using CommonTools;
using HY_UPHMgr;
using MotionIoLib;
using Newtonsoft.Json;
using OtherDevice;
using StationDemo.设备信息.helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using UserCtrl;
using UserData;

namespace StationDemo
{

    public class Param_Load
    {
        //public ParamSet 出图图像宽 = new ParamSet()
        //{
        //    _enuValType = ParamSetUnit.intUnit,
        //    _strParamUnit = "pix",
        //    _strParamValMax = 600000,
        //    _strParamValMin = 0,
        //    _strParamVal = 0,
        //    _ParamRight = UserRight.Operator,
        //    _ParamClass = "出图",
        //    b_IsStartCheck = true,
        //};
        //public ParamSet 出图图像高 = new ParamSet()
        //{
        //    _enuValType = ParamSetUnit.intUnit,
        //    _strParamUnit = "pix",
        //    _strParamValMax = 600000,
        //    _strParamValMin = 0,
        //    _strParamVal = 0,
        //    _ParamRight = UserRight.Operator,
        //    _ParamClass = "出图",
        //    b_IsStartCheck = true,
        //};


        public ParamSet 屏蔽扫码 = new ParamSet()
        {
            _enuValType = ParamSetUnit.boolUnit,
            _strParamUnit = "屏蔽扫码",
            _strParamValMax = true,
            _strParamValMin = false,
            _strParamVal = false,
            _ParamRight = UserRight.Operator,
            _ParamClass = "扫码",
            b_IsStartCheck = true,
        };
        //public ParamSet 屏蔽电压电流测试 = new ParamSet()
        //{
        //    _enuValType = ParamSetUnit.boolUnit,
        //    _strParamUnit = "屏蔽电压电流测试",
        //    _strParamValMax = true,
        //    _strParamValMin = false,
        //    _strParamVal = false,
        //    _ParamRight = UserRight.Operator,
        //    _ParamClass = "综合",
        //    b_IsStartCheck = true,
        //};
        public ParamSet 键盘模式 = new ParamSet()
        {
            _enuValType = ParamSetUnit.boolUnit,
            _strParamUnit = "键盘模式",
            _strParamValMax = true,
            _strParamValMin = false,
            _strParamVal = false,
            _ParamRight = UserRight.Operator,
            _ParamClass = "扫码",
            b_IsStartCheck = true,
        };

        public ParamSet 扫码超时时间 = new ParamSet()
        {
            _enuValType = ParamSetUnit.intUnit,
            _strParamUnit = "扫码超时时间",
            _strParamValMax = 600000,
            _strParamValMin = 0,
            _strParamVal = 60000,
            _ParamRight = UserRight.Operator,
            _ParamClass = "扫码",
            b_IsStartCheck = true,
        };

        public ParamSet 是否提前扫码 = new ParamSet()
        {
            _enuValType = ParamSetUnit.boolUnit,
            _strParamUnit = "是否提前扫码",
            _strParamValMax = true,
            _strParamValMin = false,
            _strParamVal = false,
            _ParamRight = UserRight.Operator,
            _ParamClass = "扫码",
            b_IsStartCheck = true,
        };
    }
    public class Point_Load
    {
    }
    public class Config_Load
    {

        [Category("工站参数"), DisplayName("3.扫码枪"), Description("扫码枪")]
        public string str_扫码枪 { set; get; } = "扫码枪";
    }

    /// <summary>
    /// 目前这个流程只用于扫码，为了以后兼容自动上料
    /// </summary>
    public class Station_Load : CommonTools.StationbaseEx<Param_Load, Point_Load, Config_Load>
    {
        #region 变量

        private readonly int nUPHIndex = 0;

        SNScan_Base 扫码枪 => DeviceMgr.GetInstance().Function_获取串口(station_Config.str_扫码枪) as Scan_NLSFM430;

        public Station_Load(CommonTools.Stationbase station, Param_Load param, Point_Load point, Config_Load config) : base(station, param, point, config)
        {
        }


        public enum StationStep
        {
            [Description("0.初始化步骤")]
            StepInit = 100,
            [Description("1.扫码")]
            Step扫码,
            [Description("2.结束")]
            StepEnd,
        }
        #endregion

        #region 主流程
        protected override void StationWork(int step)
        {
            try
            {
                Thread.Sleep(50);
                switch (step)
                {
                    case (int)StationStep.StepInit:
                        DelCurrentStep();
                        PushMultStep((int)StepInitRun());
                        break;
                    case (int)StationStep.Step扫码:
                        DelCurrentStep();
                        PushMultStep((int)Step扫码());
                        break;
                    case (int)StationStep.StepEnd:
                        DelCurrentStep();
                        PushMultStep((int)StepEnd());
                        break;
                }
            }
            catch (Exception ex)
            {
                LogHelper.OnTest_ShowLog(Name, $"{Name} 发生错误:{ex.StackTrace},{ex.Message}", LogType.Err);
                StationMgr.GetInstance().Stop();
            }
        }

        protected override bool InitStation()
        {
            DelCurrentStep();
            PushMultStep((int)StepInitRun());
            return true;
        }
        #endregion

        #region 方法

        public StationStep StepInitRun(bool bmanual = false)
        {
            UPHTimeMgr.Instance.AddTimeBeatType(Name);
            LogHelper.OnTest_ShowLog(Name, $"上料站，StepInitRun", LogType.Warn);
            return StationStep.Step扫码;
        }

        private string SN = "";
        public StationStep Step扫码(bool bmanual = false)
        {
            StationStateHelper.OnTest_ShowStep(Name, "请扫码", LogType.Warn);
            LogHelper.OnTest_ShowLog(Name, $"请扫码", LogType.Warn);
            
            if (!Function_扫码(ref SN))
            {
                return StationStep.Step扫码;
            }

            LogHelper.OnTest_ShowLog(Name, $"扫码成功，条码为：{SN}", LogType.Warn);

            UPHTimeMgr.Instance.AddData(nUPHIndex, Name, $"扫码完成");
            SNHelper.OnTest_ShowSN("SN", SN);
            if (Param_System.Instance.是否开启Mes._strParamVal)
            {
                //进站
                bool res = Function_进站(SN, out string msg);
                if (res)
                {
                    LogHelper.OnTest_ShowLog("MES", $"条码【{SN}】进站成功", LogType.Warn);
                }
                else
                {
                    WaranResult result = AlarmMgr.GetIntance().WarnWithDlg((int)AlarmList.MES进站失败, new string[] { "重试" }, new string[] { $"条码【{SN}】进站失败原因：{msg}，请重新扫码" });
                    if (result == WaranResult.Custom1)
                    {
                        LogHelper.OnTest_ShowLog("MES", $"条码【{SN}】进站失败,失败原因：{msg}", LogType.Warn);
                        LogHelper.OnTest_ShowLog("MES", "请重新扫码进站：", LogType.Warn);
                        Thread.Sleep(200);
                        return StationStep.Step扫码;
                    }



                }

                UPHTimeMgr.Instance.AddData(nUPHIndex, Name, $"进站完成");
            }

            return StationStep.StepEnd;
        }

        StationStep StepEnd(bool bmanual = false)
        {
            Station_三角测量.SetSN(SN);
            return StationStep.StepInit;
        }
        public override void StopDeal()
        {
        }


        public bool Function_工站回零()
        {
            bool bResult = true;
            return bResult;
        }

        #region MES

        public bool Function_进站(string SN, out string msg)
        {
            msg = "";
            return true;

        }


        #endregion

        public bool Function_扫码(ref string strSN)
        {
            if (sys.g_AppMode == AppMode.AirRun)
            {
                strSN = "空跑" + DateTime.Now.ToString("yyyyMMddHHmmss");
                return true;
            }
            if (station_Param.屏蔽扫码._strParamVal)
            {
                strSN = DateTime.Now.ToString("yyyyMMddHHmmss");
                return true;
            }
            if (station_Param.键盘模式._strParamVal)
            {

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                //SNHelper.OnTest_ReflushSN("SN");
                while (true)
                {

                    if (GlobalVariable.g_StationState == StationState.StationStateEmg)
                        return false;
                    if (UserConfig.b_isScan)
                    {
                        UserConfig.b_isScan = false;
                        strSN = UserConfig.str_SN;
                        if (strSN == string.Empty /*|| strSN.Length != Param_System.Instance.SN长度._strParamVal || !strSN.Contains(Param_System.Instance.SN固定字符._strParamVal)*/)
                        {
                            AlarmMgr.GetIntance().WarnWithDlg(AlarmList.产品SN校验错误.GetHashCode(), new string[] { "重试" }, new string[] { $"产品SN校验错误，读取内容=[{strSN}]" });
                            // SNHelper.OnTest_ReflushSN("SN");

                            return false;
                        }
                        else
                        {

                            LogHelper.OnTest_ShowLog(Name, $"读取产品SN=[{strSN}]", LogType.Info);
                            //LogHelper.OnTest_ShowLog(Name, $"等待双按钮启动", LogType.Warn);
                            //StationStateHelper.OnTest_ShowStep(Name, $"{Name} 等待双按钮启动", LogType.Warn);
                            break;

                        }
                    }
                    Thread.Sleep(10);
                    if (stopwatch.ElapsedMilliseconds > station_Param.扫码超时时间._strParamVal)
                    {
                        AlarmMgr.GetIntance().WarnWithDlg(AlarmList.等到扫码超时.GetHashCode(), new string[] { "重试" }, new string[] { $"SN读取超时，读取内容=[{strSN}]，请重试" });
                        stopwatch.Restart();
                    }
                }

            }
            else
            {

                if (扫码枪?.Fucntion_获取SN码(Param_System.Instance.SN长度._strParamVal, ref strSN, station_Param.扫码超时时间._strParamVal) == 0)
                //if (扫码枪?.Function_触发扫码(Param_System.Instance.SN长度._strParamVal, ref strSN, station_Param.扫码超时时间._strParamVal))
                {
                    strSN = strSN.Replace("\r", "");

                    if (strSN.Contains(Param_System.Instance.SN固定字符._strParamVal))
                    {

                        SNHelper.OnTest_ShowSN("SN", strSN);
                        LogHelper.OnTest_ShowLog(Name, $"读取产品SN=[{strSN}]", LogType.Info);

                        StationStateHelper.OnTest_ShowStep(Name, $"{Name} 等待双按钮启动", LogType.Warn);
                        return true;
                    }
                    else
                    {
                        AlarmMgr.GetIntance().WarnWithDlg(AlarmList.产品SN校验错误.GetHashCode(), new string[] { "重试" }, new string[] { $"产品SN校验错误，读取内容=[{strSN}]" });
                        return false;
                    }

                }
                else
                {
                    AlarmMgr.GetIntance().WarnWithDlg(AlarmList.等到扫码超时.GetHashCode(), new string[] { "重试" }, new string[] { $"SN读取超时，读取内容=[{strSN}]，请重试" });
                    return false;
                }

            }
            return true;

        }

        #endregion

    }
}
